<template>
	<div class="app-container">
		<section>
			<div class="contentBox">
				<div class="title">
					<span>{{ $route.query.title }}</span>
				</div>
				<div class="content">
					<el-form ref="form" :model="form" :rules="rules" class="form" label-width="130px"
						v-loading="loadingForm">
						<el-form-item label="项目名称：" prop="name" style="width: 100%">
							<el-input v-model="form.name" placeholder="请输入"></el-input>
						</el-form-item>
						<el-form-item label="项目分类：" prop="cate_id" style="width: 100%">
							<el-select v-model="form.cate_id" placeholder="请选择" style="width: 250px">
								<el-option v-for="item in cateList" :key="item.id" :label="item.name"
									:value="item.id"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item v-if="form.id" label="项目Id" prop="name" style="width: 100%">
							<el-input v-model="form.id" placeholder="请输入"></el-input>
						</el-form-item>
						<el-form-item label="项目时长：" prop="duration" class="timerInput" style="width: 100%">
							<el-input v-model="form.duration" placeholder="请输入"></el-input>
							<span>分钟</span>
						</el-form-item>
						<el-form-item style="width: 100%" label="标准价格:" prop="price" class="timerInput">
							<el-input v-model="form.price" placeholder="请输入"></el-input>
							<span>元</span>
						</el-form-item>
						<el-form-item style="width: 100%" label="使用次数:" prop="use_num" class="timerInput">
							<el-input v-model="form.use_num" placeholder="请输入"></el-input>
							<span>次</span>
						</el-form-item>
						<!-- <el-form-item label="会员价格:" prop="vip_price" class="timerInput">
							<el-input
								v-model="form.vip_price"
								placeholder="请输入"
							></el-input>
							<span>元</span>
						</el-form-item>-->
						<el-form-item label="加钟价格：" prop="add_clock_price" class="timerInput" style="width: 100%">
							<el-input v-model="form.add_clock_price" placeholder="请输入"></el-input>
							<span>元/30分钟</span>
						</el-form-item>

						<el-form-item label="是否强制项目完成时长：" prop="is_open_complete" class="timerInput"
							style="width: 100%">
							<el-radio-group v-model="form.is_open_complete">
								<el-radio :label="1">是</el-radio>
								<el-radio :label="0">否</el-radio>
							</el-radio-group>
						</el-form-item>

						<el-form-item label="针对部位:" style="width: 100%" prop="limbs">
							<el-checkbox-group v-model="form.limbs" @change="changeCoupon">
								<el-checkbox :key="item.id" v-for="item in projectPart"
									:label="item.title"></el-checkbox>
							</el-checkbox-group>
						</el-form-item>

						<el-form-item label="购买过期天数" style="width: 100%" prop="expire">
							<el-input-number style="width: 250px" v-model="form.expire" :min="0" :max="999999" />
						</el-form-item>

						<el-form-item label="特别提醒：" style="width: 100%" prop="tips">
							<el-input v-model="form.tips" placeholder="请输入" type="textarea" :rows="4"></el-input>
						</el-form-item>

						<el-form-item label="项目功效标签：" style="width: 100%;">
							<el-select style="width: 250px" v-model="form.tags" placeholder="请选择" multiple>
								<el-option v-for="item in effectData" :key="item.id" :label="item.name"
									:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="机构设置：" style="width: 100%" prop="tags">
							<div class="wrap wrap-set_jigou" v-for="(ele, index) in tags" :key="index">
								<el-select filterable style="width: 250px" v-model="ele.store_id" placeholder="请选择门店"
									default-first-option multiple :filter-method="filterDropdown" @change="selectChange"
									@focus="filterDropdown('')">
									<el-option v-for="item in flierStoreList" :key="item.id" :label="item.title"
										:value="item.id"></el-option>
								</el-select>

								<!-- <el-input
									v-model="ele.ratio"
									@change="iptChange($event, index)"
									placeholder="请输入抽成比例（0-100）"
									></el-input>
									<span style="margin-left: 10px">%</span> -->
									
								<span style="margin: 0 10px">价格: </span>
								<el-input v-model="ele.price" @change="iptChange($event, index)"
									placeholder="请输入价格"></el-input>

								<span style="margin: 0 10px">加钟价格:</span>
								<el-input v-model="ele.add_clock_price" @change="iptChange($event, index)"
									placeholder="请输入加钟价格"></el-input>

								<span style="margin: 0 10px">平台抽成比例: </span>
								<el-input v-model="ele.ratio" @change="iptChange($event, index)"
									placeholder="请输入抽成比例（0-100）"></el-input>
								<span style="margin: 0 10px">%</span>

								<span style="margin: 0 10px">门店分成比例: </span>
								<el-input v-model="ele.store_ratio" @change="iptChange($event, index)"
									placeholder="请输入抽成比例（0-100）"></el-input>
								<span style="margin: 0 10px">%</span>

								<div class="tagWrap">
									<i class="el-icon-circle-plus-outline addTxt" @click="addTags()"></i>
									<i v-if="index > 0" class="el-icon-remove-outline deTxt"
										@click="delTags(index)"></i>
								</div>
							</div>
						</el-form-item>
						<el-form-item label="项目介绍：" style="width: 100%" prop="desc">
							<el-input v-model="form.desc" placeholder="请输入" type="textarea" :rows="4"></el-input>
						</el-form-item>
						<el-form-item label="封面图:" style="width: 100%" ref="pic" prop="pic">
							<vs-uploading width="120px" @verify="verify('pic', $event)"
								v-model="form.pic"></vs-uploading>
						</el-form-item>
						<el-form-item label="项目图片:" style="width: 100%" ref="pics" prop="pics">
							<vs-uploading width="120px" @verify="verify('pics', $event)"
								v-model="form.pics"></vs-uploading>
						</el-form-item>
						<el-form-item label="图文详情：" style="width: 100%" prop="content">
							<div id="edit" ref="edit"></div>
						</el-form-item>
						<el-form-item label="购买须知：" style="width: 100%" prop="notice">
							<el-input v-model="form.notice" placeholder="请输入" type="textarea" :rows="4"></el-input>
						</el-form-item>
						<!-- <el-form-item
							label="适用门店:"
							style="width: 100%"
							prop="store_ids"
							>
							<el-select
								style="width: 250px"
								v-model="form.store_ids"
								placeholder="请选择"
								multiple
							>
								<el-option
								v-for="item in storeList"
								:key="item.id"
								:label="item.title"
								:value="item.id"
								>
								</el-option>
							</el-select>
							</el-form-item>-->
					</el-form>
					<div style="margin-top: 40px">
						<el-button style="width: 110px" @click="$router.go(-1)">取消</el-button>
						<el-button type="primary" style="width: 110px" @click="save">保存</el-button>
					</div>
				</div>
			</div>
		</section>
	</div>
</template>
<script>
import { number } from "echarts";
import VsUploading from "../../components/VsUploading";
import E from "wangeditor";
export default {
	components: {
		VsUploading,
	},
	data() {
		var url = (rule, value, callback) => {
			console.log(rule, value, callback);
			// 图片验证
			let obj = this.form[rule.field];
			if (Object.prototype.toString.call(obj) == "[object Array]") {
				console.log("@@@@", obj);
				if (!obj.length) return callback(new Error("请上传图片!"));
			} else if (!obj) {
				//hasFmt设置为true/false
				return callback(new Error("请上传图片!"));
			}
			callback();
		};
		return {
			cateList: [],
			value1: false,
			editor: "",
			storeList: [],
			flierStoreList: [],
			effectData: [],
			form: {
				add_clock_price: "",
				add_clock_price: 0,
				expire: "",
				name: "",
				pic: "",
				duration: "",
				use_num: "",
				price: "",
				// vip_price: "",
				cate_id: "",
				pics: [],
				limbs: [],
				tips: [],
				tags: [],
				desc: "",
				content: "",
				notice: "",
				sort: "",
				id: "",
				stores: [],
				projectPart: [],
				// store_ids: []
			},
			rules: {
				pic: { required: true, validator: url },
				pics: { required: true, validator: url },
				// add_clock_price: [
				// 	{ required: true, message: "请输入加钟价格", trigger: "blur" },
				// ],
				is_open_complete: [
					{
						required: true,
						message: "请选择是否强制项目完成时长",
						trigger: "blur",
					},
				],
				expire: [
					{ required: true, message: "请输入购买过期天数", trigger: "blur" },
				],
				name: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
				duration: [
					{ required: true, message: "请输入项目时长", trigger: "blur" },
				],
				use_num: [
					{ required: true, message: "请输入使用次数", trigger: "blur" },
				],
				cate_id: [
					{ required: true, message: "请选择项目分类", trigger: "change" },
				],
				price: [{ required: true, message: "请输入标准价格", trigger: "blur" }],
				// vip_price: [
				//   { required: true, message: "请输入会员价格", trigger: "blur" },
				// ],
				limbs: [
					{ required: true, message: "请选择针对部位", trigger: "change" },
				],
				tips: [{ required: true, message: "请输入特别提醒", trigger: "blur" }],
				desc: [{ required: true, message: "请输入项目介绍", trigger: "blur" }],
				notice: [
					{ required: true, message: "请输入购买须知", trigger: "blur" },
				],
				// store_ids: [
				//   { required: true, message: "请选择门店", trigger: "change" },
				// ],
			},
			tags: [{ ratio: "", store_id: [], price: "", add_clock_price: "", store_ratio: "" }],
			roleList: [],
			loadingForm: false,
		};
	},
	async created() {
		await this.getAllStoreList();
		if (this.$route.query.id) {
			this.form.id = this.$route.query.id;
			await this.getDetails();
		} else {
			this.$nextTick(() => {
				this.getEdit();
			});
		}
		this.GetList();
	},
	mounted() {
		this.getProjectPart();
		this.getCate();
	},
	methods: {
		async getProjectPart() {
			let { code, data } = await this.$Http.getProjectPart({ is_all: "1" });
			if (code) {
				this.projectPart = data;
			}
		},
		selectChange(e, b) {
			console.log(55656, e, b);
		},
		iptChange(e, i) {
			console.log(444, typeof e !== "number", isNaN(e));
			let pls = +e;
			if (typeof pls !== "number" || isNaN(pls)) {
				this.$message.error("请输入纯数字");
				this.tags[i].ratio = "";
				return;
			}
			if (pls < 0 && pls > 100) {
				this.tags[i].ratio = "";
				this.$message.error("比例区间0-100");
				return;
			}
			// this.tags[i].ratio = pls
		},
		// 项目功效
		async GetList() {
			let { code, data } = await this.$Http.projectGetTags(this.paging);
			if (code) {
				this.effectData = data;
				console.log(232, this.effectData);
			}
		},
		// 获取全部门店
		async getAllStoreList() {
			let { code, data } = await this.$Http.homegetStore();
			if (code) {
				this.storeList = data;
				this.flierStoreList = data;
			}
		},
		changeCoupon(e) {
			console.log(this.form.limbs, "8888888888888");
		},
		delTags(index) {
			if (this.tags.length <= 1) {
				this.$message.error("至少保留一个");
				return;
			}
			this.tags.splice(index, 1);
		},
		addTags() {
			this.tags.push({ ratio: "", store_id: [], price: "", add_clock_price: "", store_ratio: "" });
		},
		verify(hasFmt, sta) {
			if (sta) {
				this.$refs[hasFmt].validate();
			} else this.$refs[hasFmt].clearValidate();
		},
		async getDetails() {
			this.loadingForm = true;
			let { code, data } = await this.$Http.getProject(this.form);
			if (code) {
				this.getEdit();
				this.form = {
					add_clock_price: data.add_clock_price,
					is_open_complete: data.is_open_complete,
					expire: data.expire,
					name: data.name,
					pic: data.pic,
					duration: data.duration,
					use_num: data.use_num,
					price: data.price,
					// vip_price: data.vip_price,
					cate_id: data.cate_id,
					tips: data.tips,
					desc: data.desc,
					notice: data.notice,
					sort: data.sort,
					id: data.id,
					limbs: [],
					tags: [],
					stores: [],
					// store_ids: [],
				};
				// console.log(54656, data.store_id)
				// if (data.store_id != null) {
				//   let ids = data.store_id.toString()
				//   this.form.store_ids = ids.split(',');
				//   // this.form.store_id = store_id.map(Number);
				//   this.form.store_ids.forEach((item) => {
				//     item = +item
				//   })
				//   // this.form.store_id = store_id;
				//   console.log(this.form.store_id, "this.form.store_id");
				// }
				// this.tags = data.stores.length > 0 ? data.stores : [{ ratio: "", store_id: '' }]
				if (data.stores.length > 0) {
					// let newData = []
					// data.stores.forEach(item => {
					//   newData.push(item.store_id)
					// })
					// this.tags = [{ratio: data.stores[0].ratio, store_id: newData}]

					// 1. 使用 reduce 按 ratio 分组（统一转为字符串比较，避免数字和字符串的差异）
					const groupedData = data.stores.reduce((acc, item) => {
						const { ratio, add_clock_price, store_ratio, price, storeIds } = item;
						const ratioKey = [ratio, add_clock_price, store_ratio, price].join(","); // 统一转为字符串，避免 3 和 "3" 被视为不同
						if (!acc[ratioKey]) {
							acc[ratioKey] = [];
						}
						acc[ratioKey].push(item.store_id);
						return acc;
					}, {});
					console.log(Object.entries(groupedData), "groupedData");
					// 2. 转换为目标格式 [{ ratio: X, store_id: [...] }, ...]
					const result = Object.entries(groupedData).map(
						([ratios, ids]) => {
							const [ratio, add_clock_price, store_ratio, price] = ratios.split(","); // 还原原始值（数字或字符串）
							return {
								ratio: isNaN(ratio) ? ratio : Number(ratio), // 还原原始类型（数字或字符串）
								add_clock_price: isNaN(add_clock_price) ? add_clock_price : Number(add_clock_price),
								store_ratio: isNaN(store_ratio) ? store_ratio : Number(store_ratio),
								price: isNaN(price) ? price : Number(price),
								store_id: ids,
							}
						}
					);
					this.tags = result;

				} else {
					this.tags = [{ ratio: "", store_id: [], price: "", add_clock_price: "", store_ratio: "" }];
				}

				if (data.tags != null && data.tags.length > 0) {
					let pl = data.tags.map((item) => item.tags && item.tags.id)
					this.form.tags = pl
				}
				console.log(545, this.form.tags, data.tags)

				this.form.limbs = data.limbs ? data.limbs.split(",") : [];
				// this.form.limbs = limbs.filter(item => !isNaN(item));
				// let tags = data.tags.split(",");
				// this.tags = [];
				// tags.forEach((ele) => {
				//   let obj = {
				//     title: ele,
				//   };
				//   this.tags.push(obj);
				// });
				let arrs = [];
				data.pics.forEach((ele) => {
					arrs.push(ele.pic);
				});
				this.form.pics = arrs;
				this.editor.txt.html(data.content);
				this.loadingForm = false;
			}
		},
		async getCate() {
			let { code, data } = await this.$Http.getCate();
			if (code) {
				this.cateList = data;
			}
		},
		save() {
			this.$refs.form.validate(async (valid) => {
				if (valid) {
					if (!this.form.content) {
						this.$message.error("请输入图文详情");
						return;
					}
					// if (!this.tags[0].title) {
					//   this.$message.error("请输入标签");
					//   return false;
					// }
					// let arr = [];
					// for (let index = 0; index < this.tags.length; index++) {
					//   if (!this.tags[index].title) {
					//     this.$message.error(`标签${index + 1}不能为空`);
					//     return false;
					//   } else {
					//     arr.push(this.tags[index].title);
					//   }
					// }
					// this.form.tags = arr.join(",");
					this.form.customize_id = localStorage.getItem("customize_id") || "";
					this.form.stores = this.tags;
					console.log(77, this.tags);

					let plData = JSON.parse(JSON.stringify(this.form));
					plData.limbs = this.form.limbs.join(",");
					// this.form.store_ids = this.form.store_ids.join(",");

					let newObj = [];
					for (let j = 0; j < plData.stores.length; j++) {
						if (plData.stores[j].ratio == "") {
							return this.$message.error("请输入平台抽成比例");
						} else if (plData.stores[j].store_ratio == "") {
							return this.$message.error("请输入门店分成比例");
						} else if (plData.stores[j].add_clock_price == "") {
							return this.$message.error("请输入加钟价格");
						} else if (plData.stores[j].ratio == "") {
							return this.$message.error("请输价格");
						}

						let newdata = plData.stores[j].store_id || [];
						for (let i = 0; i < newdata.length; i++) {
							newObj.push({
								ratio: plData.stores[j].ratio,
								price: plData.stores[j].price,
								add_clock_price: plData.stores[j].add_clock_price,
								store_ratio: plData.stores[j].store_ratio,
								store_id: newdata[i],
							});
						}
					}

					console.log(888, newObj);
					plData.stores = newObj;
					plData.tags = this.form.tags.join(",");

					console.log(66666, plData, newObj);
					// return
					let { code, data } = await this.$Http.setProject(plData);
					if (code) {
						if (this.form.id) {
							this.$message.success("编辑成功");
						} else {
							this.$message.success("添加成功");
						}
						this.$router.go(-1);
					}
				} else {
					return false;
				}
			});
		},
		// 富文本编辑
		getEdit() {
			this.editor = new E(this.$refs.edit);
			this.editor.config.onchange = (html) => {
				this.form.content = html;
			};
			this.editor.config.customUploadImg = (resultFiles, insertImgFn) => {
				let formData = new window.FormData();
				formData.append("files", resultFiles[0]);
				this.$Http.upload(formData).then((res) => {
					if (res.status) {
						this.$message({
							message: "上传成功",
							type: "success",
						});
						insertImgFn(res.data);
					}
				});
			};
			this.editor.config.customUploadVideo = (resultFiles, insertVideoFn) => {
				let formData = new window.FormData();
				formData.append("files", resultFiles[0]);
				this.$Http.upload(formData).then((res) => {
					if (res.status) {
						this.$message({
							message: "上传成功",
							type: "success",
						});
						insertVideoFn(res.data);
					}
				});
			};
			this.editor.create();
			this.editor.txt.html(this.form.content);
		},

		createFuzzyRegex(input) {
			// 转义特殊字符
			const escaped = input.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
			// 在每个字符间插入 .*? 实现模糊匹配
			return new RegExp(escaped.split("").join(".*?"), "i");
		},
		filterDropdown(searchText) {
			const regex = this.createFuzzyRegex(searchText);
			this.flierStoreList = this.storeList.filter((option) =>
				regex.test(option.position)
			);
		},
	},
};
</script>

<style lang="scss" scoped>
::v-deep {
	.w-e-text-container {
		z-index: 1 !important; // 这是内容框
	}

	.w-e-menu {
		z-index: 2 !important; // 这是工具栏
	}

	.w-e-text {
		z-index: 1 !important; // 这是内容框
	}
}

.app-container {
	section {
		.contentBox {
			background: #fff;
			border-radius: 8px;
			padding: 0 24px 20px;
			min-width: 900px;
			min-height: calc(100vh - 165px);

			.title {
				line-height: 70px;
				font-size: 18px;
				font-weight: 600;
				color: #383b40;

				.el-icon-close {
					cursor: pointer;
				}
			}
		}

		.content {
			max-width: 1000px;
			height: 100%;

			.form {
				display: flex;
				flex-wrap: wrap;
				justify-content: flex-start;
			}
		}
	}
}

::v-deep {
	.el-input {
		width: 250px;
	}
}

.timerInput {
	.el-input {
		width: 120px;
		margin-right: 15px;
	}
}

.wrap {
	display: flex;

	::v-deep {
		.el-input {
			width: 200px;
			display: block;
			margin-bottom: 20px;
		}

		.el-input:last-child {
			margin-bottom: 0;
		}
	}
}

.wrap-set_jigou {
	border: 1px solid #dcdfe6;
	padding: 10px;
	border-radius: 5px;
	margin-bottom: 10px;
}

::v-deep {
	.w-e-toolbar {
		z-index: auto !important;
	}

	.w-e-menu {
		z-index: 2 !important;
	}

	.w-e-text-container {
		z-index: 1 !important;
	}
}

p {
	margin: 0;
}

.addTxt {
	color: #1890ff;
	margin-right: 10px;
}

.tagWrap {
	display: flex;
	margin-left: 20px;

	i {
		font-size: 22px;
		margin-right: 15px;
		margin-top: 8px;
	}

	.deTxt {
		color: #f00;
	}
}
</style>
